package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Report;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author wjs
 * @version 1.0
 * @date 2022/1/9 0009 上午 10:10
 */
@DubboService
public class ReportApiImpl implements ReportApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Report save(Report report) {
        return mongoTemplate.save(report);
    }

    @Override
    public Report findById(String id) {
        return mongoTemplate.findById(new ObjectId(id),Report.class);
    }

    @Override
    public List<Report> findByLevel(Integer level) {
        Query query = Query.query(Criteria.where("level").is(level));
        return mongoTemplate.find(query,Report.class);
    }

    @Override
    public ObjectId findIdByUserId(Long userId, Integer star) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("star").is(star)).with(Sort.by(Sort.Order.desc("created")));
        List<Report> reports = mongoTemplate.find(query, Report.class);
        if(reports.isEmpty()){
            return null;
        }
        return reports.get(0).getId();
    }


}
